package com.qf.smartdevice.controller;

import com.github.pagehelper.PageInfo;
import com.qf.smartdevice.constans.ResultCode;
import com.qf.smartdevice.dto.R;
import com.qf.smartdevice.dto.UserDto;
import com.qf.smartdevice.exceptions.UpdateException;
import com.qf.smartdevice.pojo.User;
import com.qf.smartdevice.service.IMenuService;
import com.qf.smartdevice.service.IUsersService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/users")
@RestController
public class UserController {
    @Autowired
    private IUsersService usersService;

    @RequestMapping("/users")
    public R getAllUsers(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String username, @RequestParam(defaultValue = "-100") int status) {

        PageInfo<User> userList = usersService.findAllUserByPage(page, limit, username, status);

        return R.setOk(userList);
    }

    @PostMapping("/user")
    public R addUser(@RequestBody UserDto user) {
        usersService.addUser(user);

        return R.setOk(user);
    }

    @DeleteMapping("/users")
    public R deleteByIds(Integer[] ids) {
        usersService.deleteUsersByIdS(ids);
        return R.setOk(null);
    }

    @PutMapping("/user")
    public R updateUser(@RequestBody UserDto userDto) {
//      没传递数据或者没传递ID  不可以更新
        if (userDto == null || userDto.getId() == null || userDto.isNull()) {
            throw new UpdateException("没有填写更新需要的数据", ResultCode.NULL_DATA);
        }
//        能否立刻更新
        if (StringUtils.isEmpty(userDto.getPassword())) {
            userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes(StandardCharsets.UTF_8)));
        }
        usersService.updateUser(userDto);
        return R.setOk(null);
    }


}
